package com.sr.examination.user.wallet;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.sr.examination.MyApplication;
import com.sr.examination.R;
import com.sr.examination.net.Net;
import com.sr.examination.user.Account;
import com.tl.commonlibrary.network.ErrorResponse;
import com.tl.commonlibrary.network.RequestListener;
import com.tl.commonlibrary.network.bean.base.BaseBean;
import com.tl.commonlibrary.tool.NumberUnit;
import com.tl.commonlibrary.tool.UIUtils;
import com.tl.commonlibrary.ui.BaseFragmentActivity;
import com.tl.commonlibrary.ui.adapter.ListViewAdapter;
import com.tl.commonlibrary.ui.adapter.ViewHolder;
import com.tl.commonlibrary.ui.beans.AliPayResultBean;
import com.tl.commonlibrary.ui.beans.RechargeBean;
import com.tl.commonlibrary.ui.beans.User;
import com.tl.commonlibrary.ui.widget.TitleBar;
import com.tl.libmanager.PayEntrance;
import com.tl.libmanager.PluginManager;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * Created by JongSung on 18/2/6.
 */

public class WalletActivity extends BaseFragmentActivity implements AdapterView.OnItemClickListener, ListViewAdapter.OnListViewAdapterListener<RechargeBean> {
    public static void start(Context context) {
        if (Account.isLogged(context)) {
            Intent starter = new Intent(context, WalletActivity.class);
            context.startActivity(starter);
        }
    }

    private ListView rechargeLView;
    private ListViewAdapter<RechargeBean> adapter;
    private TextView coinTView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_wallet);
        setTitle(getString(R.string.my_coin));
        getTitleBar().addAction(new TitleBar.TextAction(getString(R.string.my_wallet_detail)) {
            @Override
            public void performAction(View view) {
                WalletDetailActivity.start(context);
            }
        });
        findViewById(R.id.payWXBtn).setOnClickListener(this);
        findViewById(R.id.payAliBtn).setOnClickListener(this);
        rechargeLView = findViewById(R.id.rechargeLView);
        rechargeLView.setDivider(new ColorDrawable(0x00000000));
        rechargeLView.setDividerHeight(0);
        rechargeLView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
        coinTView = findViewById(R.id.coinTView);
        coinTView.setText(new NumberUnit(Account.getUser().getGoldCoin()).get2F());
        MyApplication.get().updateUserInfo(new MyApplication.OnUpdateUserInfoListener() {
            @Override
            public void onUpdateUserInfo(User user) {
                coinTView.setText(new NumberUnit(Account.getUser().getGoldCoin()).get2F());
            }
        });
        findViewById(R.id.contentLayout).setVisibility(View.GONE);
        getRechargeList();
    }

    private void getRechargeList() {
        showLoading();
        Net.getRechargeList(new RequestListener<BaseBean<List<RechargeBean>>>() {
            @Override
            public void onSuccess(Call<BaseBean<List<RechargeBean>>> call, BaseBean<List<RechargeBean>> response) {
                if (response.isSuccessful()) {
                    adapter = new ListViewAdapter<RechargeBean>(context, response.data, R.layout.item_recharge, WalletActivity.this);
                    rechargeLView.setOnItemClickListener(WalletActivity.this);
                    rechargeLView.setAdapter(adapter);
                    findViewById(R.id.contentLayout).setVisibility(View.VISIBLE);
                }
                dismissAll();
            }

            @Override
            public void onFailed(Call<BaseBean<List<RechargeBean>>> call, ErrorResponse errorResponse) {
                dismissAll();
            }
        });
    }

    private void payAli(String productId) {
        PayEntrance entrance = PluginManager.get().getPayEntrance();
        if (entrance != null) {
            entrance.payAli(this, productId, new PayEntrance.OnPayResultListener() {
                @Override
                public void onPaySuccess(int payWay, Message message) {
                    if (message != null) {
                        if (message.obj instanceof AliPayResultBean) {
                            AliPayResultBean bean = (AliPayResultBean) message.obj;
                            User user = Account.getUser();
                            if (user != null) {
                                user.setGoldCoin(bean.getUserCoins());
                                Account.setUser(user);
                                coinTView.setText(new NumberUnit(user.getGoldCoin()).get2F());
                                UIUtils.showToast("恭喜，金币充值成功啦~");
                            }
                        }
                    }
                }

                @Override
                public void onPayFailed(int payWay, String code, String message) {

                }
            });
        }
    }

    private void payWx(String productId) {
        PayEntrance entrance = PluginManager.get().getPayEntrance();
        if (entrance != null) {
            entrance.payWX(this, productId, new PayEntrance.OnPayResultListener() {
                @Override
                public void onPaySuccess(int payWay, Message message) {

                }

                @Override
                public void onPayFailed(int payWay, String code, String message) {

                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.payWXBtn:
                int checkedPosition = rechargeLView.getCheckedItemPosition();
                if (checkedPosition >= 0 && checkedPosition < adapter.getCount()) {
                    payWx(adapter.getItem(checkedPosition).getProductId());
                } else {
                    UIUtils.showToast(getString(R.string.attention_recharge_money_empty));
                }
                break;
            case R.id.payAliBtn:
                checkedPosition = rechargeLView.getCheckedItemPosition();
                if (checkedPosition >= 0 && checkedPosition < adapter.getCount()) {
                    payAli(adapter.getItem(checkedPosition).getProductId());
                } else {
                    UIUtils.showToast(getString(R.string.attention_recharge_money_empty));
                }
                break;
        }
    }

    @Override
    public void onFragmentTrigger(int tag, Bundle bundle) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        SparseBooleanArray booleanArray = rechargeLView.getCheckedItemPositions();
//
    }

    @Override
    public void onClickViewInListItem(View v) {

    }

    @Override
    public void getView(ViewHolder viewHolder, RechargeBean entity, int position, View convertView, boolean isConvert, int itemViewType, ViewGroup parent) {
        TextView goldTView = viewHolder.getView(R.id.goldTView);
        CheckBox priceCBox = viewHolder.getView(R.id.check_box);
        View lineView = viewHolder.getView(R.id.lineView);
        goldTView.setText(entity.getName());
        priceCBox.setText("￥" + new NumberUnit(entity.getPrice()).get2F());
        if (position == adapter.getCount() - 1) {
            lineView.setVisibility(View.GONE);
        } else {
            lineView.setVisibility(View.VISIBLE);
        }
    }
}
